package com.gykj.sso.config;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.gykj.sso.util.RandomUtil;

import java.util.concurrent.TimeUnit;

public class StateEntity {

    /**
     * state 缓存 Map , 用于存储单点登录时的 URL
     * state 过期时间 60 秒
     */
    private static Cache<String, String> cache = CacheBuilder.newBuilder().expireAfterWrite(60, TimeUnit.SECONDS).build();

    public static String getState(){
        String key;
        while (true){
            key = RandomUtil.randomInt(6);
            if(!cache.asMap().containsKey(key)) {
                cache.put(key, "");// 占位，保证其他人获取不到该 code
                return key;
            }
        }
    }

    public static void setState(String key, String val){
        cache.put(key, val);
    }

    public static String getVal(String key){
        return cache.getIfPresent(key);
    }

    /**
     * 测试方法
     * @param args str
     * @throws InterruptedException e
     */
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10000; i++) {
            Thread.sleep(1000);

            String key = getState();
            setState(key, key);

            for (String tmp : cache.asMap().keySet()) {
                System.out.printf("key: %s, val: %s%n", tmp, getVal(tmp));
            }
            System.out.println("-------------------------------------------");
        }
    }
}
